<script setup>
import { onMounted, reactive, ref } from 'vue'
import { User } from "@/api"
import { ElMessage } from 'element-plus';
// 获取用户等级列表并渲染----------------------------------------------------
let tableData = ref([]);//表格数据
let level_count = ref(0)//总数
let loading = ref(false)//加载动画
let init_form = ref({
    page: 1,
    limit: 8,
    title: "",
    is_show: '',
})
// 拉取等级列表
let init_level = async () => {
    loading.value = true
    let { status, msg, data } = await User.vip_list(init_form.value)
    if (status == 200) {
        tableData.value = data.list;
        level_count.value = data.count;
        loading.value = false
    }
}
onMounted(() => {
    init_level()
})
// 获取当前页最新数据
let handlePage = async (curpage) => {
    init_form.value.page = curpage
    init_level()
}
// 设置显示隐藏
let changeShow = async (id, is_show) => {
    let { status, msg } = await User.set_show(id, is_show)
    if (status == 200) ElMessage.success(msg)
    else ElMessage.error(msg)
}

// 添加/修改等级
let level_dialog_visible = ref(false)//等级对话框开关
let level_dialog_title = ref('')//等级对话框标题
let level_form_ref = ref(null)//等级表单ref
let level_form = ref({})//等级表单对象
let level_rules = ref({})//等级输入规则
let level_form_item = ref([])
// 获取添加等级表单
let handleOpenLevelDialog = async (id) => {
    let { status, msg, data } = await User.user_level_create({ id })
    if (status == 200) {
        level_dialog_title.value = data.title
        if (!id) data.rules.unshift({ type: 'hidden', field: 'id', value: '' })
        data.rules.forEach((item) => {
            if (item.type == 'input') item.type = 'text'
            if (item.type == 'inputNumber') item.type = 'number'
            if (item.type == 'frame') item.type = 'image'
            level_form.value[item.field] = item.value;
            if (item.validate) {
                level_rules.value[item.field] = item.validate
            }
        })
        level_form_item.value = data.rules;
    }
    level_dialog_visible.value = true
}
// 保存等级
let handleSave = async () => {
    let { status, msg } = await User.save_level(level_form.value)
    if (status == 200) {
        ElMessage.success(msg)
        level_dialog_visible.value = false;
        init_level();
    } else {
        ElMessage.error(msg)
    }
}

// 删除等级
let handleDelete = (id) => {
    ElMessageBox.confirm(
        '此操作将彻底删除该等级，继续?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let { status, msg } = await User.remove_level(id)
            if (status == 200) {
                ElMessage.success(msg)
                init_level()
            } else {
                ElMessage.error(msg)
            }
        })
        .catch(() => {
            ElMessage.info('取消')
        })
}


// 图片的上传
let image_dialog_visible = ref(false)//图片对话框开关
let image_dialog_title = ref('')//图片对话框标题
let image_cate_all = ref([])//全部图片分类
let imageData = ref([]);//图片数据
let image_count = ref(0)//图片总数
let image_field = ref('')//当前编辑图片(图标or背景图)
let cur_image = ref({})//当前选中图片
let cur_index = ref(-1)//当前选中图片索引
let init_image_form = ref({
    pid: 0,
    page: 1,
    limit: 18,
})
// 拉取图片分类
let init_image_cate = async () => {
    let { status, msg, data } = await User.getImageCate()
    if (status == 200) {
        data.list.unshift({
            id: 0,
            pid: 0,
            name: '全部',
            enname: '',
            title: '全部'
        })
        image_cate_all.value = data.list;
    }
}
// 拉取图片数据
let init_image = async () => {
    let { status, msg, data } = await User.getImage(init_image_form.value)
    if (status == 200) {
        image_count.value = data.count
        imageData.value = data.list;
    }
}
// 打开图片对话框
let handleOpenImageDialog = (title, field) => {
    image_field.value = field;
    image_dialog_title.value = `请选择${title}`
    init_image_cate()
    init_image()
    image_dialog_visible.value = true;
}
// 图片翻页
let handleImagePage = async (curpage) => {
    init_image_form.value.page = curpage;
    init_image();
}
// 图片分类分页
let tabChange = async (activeName) => {
    init_image_form.value.pid = image_cate_all.value[activeName].id;
    init_image()
}
// 选中图片
let handleSelectImage = (curImg, index) => {
    if (cur_index.value !== index) {
        cur_index.value = index;
        cur_image.value = curImg;
    } else {
        cur_index.value = -1;
        cur_image.value = {};
    }
}
// 使用图片
let useImage = () => {
    level_form.value[image_field.value] = cur_image.value.att_dir;
    image_dialog_visible.value = false;
}
let removeImage=async()=>{
    let {status,msg}=await User.remove_img({ids:cur_index.value});
    if(status){
        ElMessage.success(msg)
        init_image()
    }
}
</script>
<template>
    <el-card>
        <el-row>
            <el-form style="display: flex;">
                <el-form-item style="margin-right: 20px;" label="状态">
                    <el-select v-model="init_form.is_show" clearable placeholder="请选择">
                        <el-option label="显示" value="1" />
                        <el-option label="不显示" value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="等级名称">
                    <el-input v-model="init_form.title" placeholder="请输入等级名称">
                        <template #append>
                            <el-button @click="init_level(init_form)" style="background-color: #1890ff; color: #fff;"
                                icon="Search"></el-button>
                        </template>
                    </el-input>
                </el-form-item>
            </el-form>
        </el-row>
        <el-row>
            <el-button @click="handleOpenLevelDialog('')" icon="CirclePlus" type="primary">
                添加用户等级
            </el-button>
        </el-row>
        <el-table v-loading="loading" size="large" :data="tableData" style="width: 100%; margin-top: 30px;" border :header-cell-style="{backgroundColor:'#ececec'}">
            <el-table-column prop="id" label="ID" width="70" />
            <el-table-column align="center" label="等级图标">
                <template #default="scope">
                    <el-avatar :src="scope.row.icon" fit="contain" />
                </template>
            </el-table-column>
            <el-table-column align="center" label="等级背景图">
                <template #default="scope">
                    <el-avatar shape="square" :src="scope.row.image" />
                </template>
            </el-table-column>
            <el-table-column prop="name" label="等级名称" />
            <el-table-column prop="grade" label="等级" />
            <el-table-column prop="discount" label="享受折扣" />
            <el-table-column prop="exp_num" label="经验值要求" />
            <el-table-column label="是否显示">
                <template #default="scope">
                    <el-switch @change="changeShow(scope.row.id, $event)" v-model="scope.row.is_show" :active-value="1"
                        :inactive-value="0" inline-prompt active-text="显示" inactive-text="隐藏" />
                </template>
            </el-table-column>

            <el-table-column align="center" fixed="right" label="操作" width="200">
                <template #default="scope">
                    <el-button @click="handleOpenLevelDialog(scope.row.id)" link type="primary" size="small">修改</el-button>
                    <el-button @click="handleDelete(scope.row.id)" link type="primary" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row style="margin-top: 20px;" justify="end" align="middle">
            <span style="margin-right: 10px;">共 {{ level_count }} 条</span>
            <el-pagination @current-change="handlePage" :page-size="init_form.limit" background
                layout="prev, pager, next,jumper" :total="level_count" />
        </el-row>
        <!--等级对话框 -->
        <el-dialog v-model="level_dialog_visible" :title="level_dialog_title">
            <el-form :model="level_form" ref="level_form_ref" :rules="level_rules" label-width="150px">
                <el-form-item v-for=" (item, index) in level_form_item" :label="item.title" :prop="item.field">
                    <el-radio-group v-if="item.type == 'radio'" v-model="level_form[item.field]">
                        <el-radio v-for="option in item.options" :label="option.value" size="large">
                            {{ option.label }}
                        </el-radio>
                    </el-radio-group>
                    <el-avatar @click="handleOpenImageDialog(item.title, item.field)" v-else-if="item.type == 'image'"
                        shape="square" :size="50" :src="level_form[item.field]" />

                    <el-input v-else v-model="level_form[item.field]" :type="item.type"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="level_dialog_visible = false">取消</el-button>
                    <el-button @click="handleSave" type="primary">提交</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 图片对话框 -->
        <el-dialog width="900px" @close="image_dialog_visible = false" v-model="image_dialog_visible"
            :title="image_dialog_title">
            <el-tabs @tab-change="tabChange" tab-position="left">
                <el-tab-pane v-for='(item, index) in image_cate_all' :label="item.name">
                    <el-row style="margin-top: 20px;" align="middle">
                        <el-button :disabled="cur_index == -1" @click="useImage" type="primary">使用选中图片</el-button>
                        <el-button :disabled="cur_index == -1" @click="removeImage" type="primary">删除选中图片</el-button>
                    </el-row>
                    <div class="image-container">
                        <div v-for="(image, i) in imageData" class="image-box">
                            <el-image :style="{ 'border': (i == cur_index ? '2px solid red' : '2px solid transparent') }"
                                @click="handleSelectImage(image, i)" class="el-image" style="width: 100px; height: 100px"
                                :src="image.att_dir" />
                            <div class="image-name">{{ image.real_name }}</div>
                        </div>
                    </div>
                    <el-row style="margin-top: 20px;" justify="end" align="middle">
                        <span style="margin-right: 10px;">共 {{ image_count }} 条</span>
                        <el-pagination @current-change="handleImagePage" :page-size="init_image_form.limit" background
                            layout="prev, pager, next,jumper" :total="image_count" />
                    </el-row>
                </el-tab-pane>
            </el-tabs>
        </el-dialog>
    </el-card>
</template>
<style lang="less" scoped>
.image-container {
    width: 760px;
    display: flex;
    flex-wrap: wrap;

    .image-box {
        margin: 10px 10px;

        .el-image {
            cursor: pointer;
        }

        .image-name {
            width: 100px;
            white-space: nowrap;
            /* 文本不换行 */
            overflow: hidden;
            text-overflow: ellipsis;
            /* 文本溢出时显示省略号标记... */
        }
    }
}
</style>
